﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sausage.Common;
using Sausage.Web.Code;
using Sausage.Web.DataModel;
using Sausage.Web.Domain;
using Sausage.Web.Models;

namespace Sausage.Web.Controllers
{
    /// <summary>
    /// 养护工程量控制器
    /// </summary>
    /// <remarks></remarks>
    /// <history>
    /// [zanezeng]               2012/02/21 10:06    创建
    /// </history>
    public class MaintainQuantityController : Controller
    {
        /// <summary>
        /// 默认动作。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [RequireAuthorization]
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 默认动作。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [RequireAuthorization]
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult Submit()
        {
            return View();
        }

        /// <summary>
        /// 养护工程量审核。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [RequireAuthorization]
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult Audit()
        {
            return View();
        }

        /// <summary>
        /// 养护工程量确认。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [RequireAuthorization]
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult Confirm()
        {
            return View();
        }

        /// <summary>
        /// 查看。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult ViewQuantity(Guid quantityID)
        {
            //返回视图
            return View(MaintainQuantityHelper.GetMaintainQuantityByID(quantityID));
        }

        /// <summary>
        /// 待提交养护工作量一览
        /// </summary>
        /// <param name="query">查询条件模型。</param>
        /// <returns>查询的工程项目信息列表</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult SubmittingList(JosnPagingQueryModel query)
        {
            var result = MaintainQuantityHelper.GetSubmittingList();
            //返回结果
            return new JsonNetResult()
            {
                Data = new JsonResultViewModel
                {
                    success = true,
                    data = result,
                    total = result.Count,
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query">查询条件模型。</param>
        /// <returns>查询的工程项目信息列表</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Select(JosnPagingQueryModel query)
        {
            var result = MaintainQuantityHelper.Select(query);

            //返回结果
            return new JsonNetResult()
                       {
                           Data = new JsonResultViewModel
                                      {
                                          success = true,
                                          data = result.Data,
                                          total = result.Total,
                                          message = "养护工程量加载成功！"
                                      },
                           JsonRequestBehavior = JsonRequestBehavior.AllowGet
                       };
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query">查询条件模型。</param>
        /// <returns>查询的工程项目信息列表</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult SubmitSelect(JosnPagingQueryModel query)
        {
            var result = MaintainQuantityHelper.SubmitSelect(query);

            //返回结果
            return new JsonNetResult()
            {
                Data = new JsonResultViewModel
                {
                    success = true,
                    data = result.Data,
                    total = result.Total,
                    message = "养护工程量加载成功！"
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query">查询条件模型。</param>
        /// <returns>查询的工程项目信息列表</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult AuditSelect(JosnPagingQueryModel query)
        {
            var result = MaintainQuantityHelper.AuditSelect(query);

            //返回结果
            return new JsonNetResult()
            {
                Data = new JsonResultViewModel
                {
                    success = true,
                    data = result.Data,
                    total = result.Total,
                    message = "养护工程量加载成功！"
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query">查询条件模型。</param>
        /// <returns>查询的工程项目信息列表</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult ConfirmSelect(JosnPagingQueryModel query)
        {
            var result = MaintainQuantityHelper.ConfirmSelect(query);

            //返回结果
            return new JsonNetResult()
            {
                Data = new JsonResultViewModel
                {
                    success = true,
                    data = result.Data,
                    total = result.Total,
                    message = "养护工程量加载成功！"
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        /// <summary>
        /// 详细
        /// </summary>
        /// <returns>执行结果</returns>
        /// <remarks></remarks>
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Details(Guid id)
        {
            var entity = MaintainQuantityHelper.GetMaintainQuantityByID(id);

            if (entity == null)
            {
                return Json(new JsonResultViewModel { success = true, message = "找不到此养护工程量！" },
                            JsonRequestBehavior.AllowGet);
            }

            var data = new
            {
                QuantityID = entity.QuantityID,
                OrganizationID = entity.OrganizationID,
                Organization = entity.Organization.OrganizationName,
                MaintainCode = entity.MaintainCode,
                Roadway = entity.Roadway,
                BeginStake = entity.BeginStake,
                EndStake = entity.EndStake,
                CategoryID = entity.CategoryID,
                Category = entity.MaintainCategory.CategoryName,
                Quantity = entity.Quantity,
                Unit = entity.MaintainCategory.Unit,
                Price = entity.Price,
                Amount = entity.Amount,
                CreateDate = entity.CreateDate,
                Applicant = entity.Applicant,
                ApplicationDate = entity.ApplicationDate,
                Auditor = entity.Auditor,
                AuditedDate = entity.AuditedDate,
                Approver = entity.Approver,
                ApprovedDate = entity.ApprovedDate,
                State = entity.State,
                IsDelay = entity.IsDelay,
                Memo = entity.Memo
            };

            //返回结果
            return new JsonNetResult()
                       {
                           Data = new JsonResultViewModel
                                      {
                                          success = true,
                                          total = 1,
                                          data = data,
                                          message = "加载养护工程量成功！"
                                      },
                           JsonRequestBehavior = JsonRequestBehavior.AllowGet
                       };
        }

        /// <summary>
        /// 参照
        /// </summary>
        /// <returns>执行结果</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonNetResult Reference(long? date)
        {
            //判定是否有过滤日期
            if (null == date)
            {
                //如果没有过滤日期，则返回空
                return new JsonNetResult()
                           {
                               Data = new JsonResultViewModel()
                                          {
                                              message = "加载养护工程量成功！",
                                              success = true,
                                              total = 0
                                          },
                               JsonRequestBehavior = JsonRequestBehavior.AllowGet
                           };
            }

            //创建日期
            DateTime applicationDate = new DateTime(1970, 1, 1).AddMilliseconds(date.Value).ToLocalTime();
            var data = MaintainQuantityHelper.GetMaintainQuantityListByDate(applicationDate).Select(
                item => new MaintainQuantityReference
                            {
                                QuantityID = item.QuantityID,
                                MaintainCode = item.MaintainCode,
                                Category = item.MaintainCategory.CategoryName,
                                ApplicationDate = item.ApplicationDate
                            }
                ).OrderBy(item => item.MaintainCode).ToList();

            return new JsonNetResult()
                       {
                           Data = new JsonResultViewModel()
                                      {
                                          message = "加载养护工程量成功！",
                                          success = true,
                                          data = data,
                                          total = data.Count
                                      },
                           JsonRequestBehavior = JsonRequestBehavior.AllowGet
                       };
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns>执行结果</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Delete(MaintainQuantityListRow data)
        {
            var maintainQuantity = MaintainQuantityHelper.GetMaintainQuantityByID(data.QuantityID);

            if (maintainQuantity == null)
                return Json(new JsonResultViewModel { success = false, message = "没有此工程量信息！", data = null },
                            JsonRequestBehavior.AllowGet);

            MaintainQuantityHelper.DeleteMaintainQuantity(data.QuantityID);
            return Json(new JsonResultViewModel { success = true, message = "养护工程量删除成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <returns>执行结果</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Update(MaintainQuantityListRow data)
        {
            MaintainQuantityHelper.UpdateMaintainQuantity(data);
            return Json(new JsonResultViewModel { success = true, message = "养护工程量更新成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <returns>执行结果</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult UpdateState(Guid id, int state)
        {
            MaintainQuantityHelper.UpdateMaintainQuantityState(id, state);
            return Json(new JsonResultViewModel { success = true, message = "养护工程量状态更新成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="quantityID">The quantity ID.</param>
        /// <returns>
        /// 执行结果
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult ExecuteSubmit(Guid[] quantities)
        {
            MaintainQuantityHelper.ExecuteSubmit(quantities);
            return Json(new JsonResultViewModel { success = true, message = "养护工作量提交成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="quantities">The quantities.</param>
        /// <param name="name">The auditor.</param>
        /// <returns>
        /// 执行结果
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult ExecuteAudit(Guid[] quantities, bool passed, string comment)
        {
            MaintainQuantityHelper.ExecuteAudit(quantities, passed, comment);
            return Json(new JsonResultViewModel { success = true, message = "养护工作量审核成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 批准
        /// </summary>
        /// <param name="quantities">The quantities.</param>
        /// <param name="auditor">The auditor.</param>
        /// <returns>
        /// 执行结果
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult ExecuteConfirm(Guid[] quantities, bool passed, string comment)
        {
            MaintainQuantityHelper.ExecuteConfirm(quantities, passed, comment);
            return Json(new JsonResultViewModel { success = true, message = "养护工作量审核成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <returns>创建结果。</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Create(MaintainQuantityListRow data)
        {
            string errorMessage;
            if (!Helper.CouldSet(data.ApplicationDate, out errorMessage))
                return Json(new JsonResultViewModel { success = false, message = errorMessage }, JsonRequestBehavior.AllowGet);

            MaintainQuantityHelper.CreateMaintainQuantity(data);
            return Json(new JsonResultViewModel { success = true, message = "养护工程量创建成功！" }, JsonRequestBehavior.AllowGet);
        }
    }
}
